/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.node.ForestNodeMerger;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringPool;
import org.springblade.modules.admin.entity.MaintainSignCalendar;
import org.springblade.modules.admin.enums.TaskStatusEnum;
import org.springblade.modules.admin.service.IMaintainSignCalendarService;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.mapper.DeptMapper;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.vo.*;
import org.springblade.modules.system.wrapper.DeptWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author Chill
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {
	private static final String TENANT_ID = "tenantId";
	private static final String PARENT_ID = "parentId";

	@Autowired
	private IMaintainSignCalendarService maintainSignCalendarService;

	@Override
	public List<DeptVO> lazyList(String tenantId, Long parentId, Map<String, Object> param, Boolean isSign) {
		// 设置租户ID
		if (AuthUtil.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) {
			tenantId = StringPool.EMPTY;
		}
		String paramTenantId = Func.toStr(param.get(TENANT_ID));
		if (Func.isNotEmpty(paramTenantId) && AuthUtil.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) {
			tenantId = paramTenantId;
		}
		// 判断点击搜索但是没有查询条件的情况
		if (Func.isEmpty(param.get(PARENT_ID)) && param.size() == 1) {
			parentId = 0L;
		}
		// 判断数据权限控制,非超管角色只可看到本级及以下数据
//		if (Func.toLong(parentId) == 0L && !AuthUtil.isAdministrator()) {
//			Long deptId = Func.firstLong(AuthUtil.getDeptId());
//			Dept dept = SysCache.getDept(deptId);
//			if (dept.getParentId() != 0) {
//				parentId = dept.getParentId();
//			}
//		}
		// 判断点击搜索带有查询条件的情况
		if (Func.isEmpty(param.get(PARENT_ID)) && param.size() > 1 && Func.toLong(parentId) == 0L) {
			parentId = null;
		}
		if (isSign) {
			MaintainSignCalendar maintainSignCalendar = maintainSignCalendarService.getOne(Wrappers.<MaintainSignCalendar>lambdaQuery().orderByDesc(MaintainSignCalendar::getCreateTime).last("limit 1"));
			return baseMapper.lazyListV2(tenantId, parentId, param, maintainSignCalendar.getSignSetingId().toString());
		} else {
			return baseMapper.lazyList(tenantId, parentId, param);
		}
	}

	@Override
	public List<DeptVO> tree(String tenantId, Boolean isSign) {
		String signSetingId = null;
		if (isSign) {
			MaintainSignCalendar maintainSignCalendar = maintainSignCalendarService.getOne(Wrappers.<MaintainSignCalendar>lambdaQuery().orderByDesc(MaintainSignCalendar::getCreateTime).last("limit 1"));
			signSetingId = maintainSignCalendar.getSignSetingId().toString();
		}
		return ForestNodeMerger.merge(baseMapper.tree(tenantId, isSign, signSetingId));
	}

	@Override
	public List<DeptVO> lazyTree(String tenantId, Long parentId) {
		if (BladeConstant.ADMIN_TENANT_ID.equals(tenantId)) {
			tenantId = StringPool.EMPTY;
		}
		return ForestNodeMerger.merge(baseMapper.lazyTree(tenantId, parentId));
	}

	@Override
	public String getDeptIds(String tenantId, String deptNames) {
		List<Dept> deptList = baseMapper.selectList(Wrappers.<Dept>query().lambda().eq(Dept::getTenantId, tenantId).in(Dept::getDeptName, Func.toStrList(deptNames)));
		if (deptList != null && deptList.size() > 0) {
			return deptList.stream().map(dept -> Func.toStr(dept.getId())).distinct().collect(Collectors.joining(","));
		}
		return null;
	}

	@Override
	public String getDeptIdsByFuzzy(String tenantId, String deptNames) {
		LambdaQueryWrapper<Dept> queryWrapper = Wrappers.<Dept>query().lambda().eq(Dept::getTenantId, tenantId);
		queryWrapper.and(wrapper -> {
			List<String> names = Func.toStrList(deptNames);
			names.forEach(name -> wrapper.like(Dept::getDeptName, name).or());
		});
		List<Dept> deptList = baseMapper.selectList(queryWrapper);
		if (deptList != null && deptList.size() > 0) {
			return deptList.stream().map(dept -> Func.toStr(dept.getId())).distinct().collect(Collectors.joining(","));
		}
		return null;
	}

	@Override
	public List<String> getDeptNames(String deptIds) {
		return baseMapper.getDeptNames(Func.toLongArray(deptIds));
	}

	@Override
	public List<Dept> getDeptChild(Long deptId) {
		return baseMapper.selectList(Wrappers.<Dept>query().lambda().like(Dept::getAncestors, deptId));
	}

	@Override
	public boolean removeDept(String ids) {
		Integer cnt = baseMapper.selectCount(Wrappers.<Dept>query().lambda().in(Dept::getParentId, Func.toLongList(ids)));
		if (cnt > 0) {
			throw new ServiceException("请先删除子节点!");
		}
		Integer userCount = baseMapper.selectUserCountBydeptIds(ids);
		if (userCount > 0) {
			throw new ServiceException("请先删除部门相关人员!");
		}

		//该机构或下级机构当前若存在关联维保电梯，无法删除
		boolean existRelationship = baseMapper.selectRelationCountByDeptIds(ids) > 0;
		if (existRelationship) {
			throw new ServiceException("该机构或下级机构当前仍存在关联维保电梯，无法删除!");
		}

		return removeByIds(Func.toLongList(ids));
	}

	@Override
	public boolean submit(Dept dept) {
		if (Func.isEmpty(dept.getParentId())) {
			dept.setTenantId(AuthUtil.getTenantId());
			dept.setParentId(BladeConstant.TOP_PARENT_ID);
			dept.setAncestors(String.valueOf(BladeConstant.TOP_PARENT_ID));
		}
		if (dept.getParentId() > 0) {
			Dept parent = getById(dept.getParentId());
			if (Func.toLong(dept.getParentId()) == Func.toLong(dept.getId())) {
				throw new ServiceException("父节点不可选择自身!");
			}
			dept.setTenantId(parent.getTenantId());
			String ancestors = parent.getAncestors() + StringPool.COMMA + dept.getParentId();
			dept.setAncestors(ancestors);
		}
		dept.setIsDeleted(BladeConstant.DB_NOT_DELETED);
		return saveOrUpdate(dept);
	}

	@Override
	public List<DeptVO> search(String deptName, Long parentId) {
		String tenantId = AuthUtil.getTenantId();
		LambdaQueryWrapper<Dept> queryWrapper = Wrappers.<Dept>query().lambda();
		if (Func.isNotEmpty(tenantId)) {
			queryWrapper.eq(Dept::getTenantId, tenantId);
		}
		if (Func.isNotEmpty(deptName)) {
			queryWrapper.like(Dept::getDeptName, deptName);
		}
		if (Func.isNotEmpty(parentId) && parentId > 0L) {
			queryWrapper.eq(Dept::getParentId, parentId);
		}
		List<Dept> deptList = baseMapper.selectList(queryWrapper);
		return DeptWrapper.build().listNodeVO(deptList);
	}

	@Override
	public List<DeptMemberVO> deptMemberAmountTree(String tenantId, Long deptId, Integer level) {
		List<DeptMemberVO> result = baseMapper.deptMemberAmountTree(tenantId, deptId, level);
		if (Func.isNotEmpty(result)) {
			result = result.stream().filter(e -> e.getType() == 1).collect(Collectors.toList());
		}
		return result;
	}

	@Override
	public List<UserTaskAmountVO> getDeptUsers(Long deptId) {
		return baseMapper.getDeptUsers(deptId, TaskStatusEnum.BY_DISABLE.getStatus());
	}

	@Override
	public List<DeptVO> deptPlanTree(String tenantId, String yearMonth) {
		return ForestNodeMerger.merge(baseMapper.deptPlanTree(tenantId, yearMonth));
	}

	@Override
	public List<UserAncestorsVO> getAncestorsByUserIds(List<Long> userIds) {
		return baseMapper.getAncestorsByUserIds(userIds);
	}

	@Override
	public List<String> getAncestorsByUserId(Long userId) {
		return baseMapper.getAncestorsByUserId(userId);
	}

	@Override
	public List<Dept> getDeptByParentName(String deptName) {
		return baseMapper.getDeptByParentName(deptName);
	}

	@Override
	public Integer getElevatorCountById(Long deptId) {
		//获取子部门id集合
		List<Long> ids = new ArrayList<>();
		ids.add(deptId);
		List<Dept> deptChild = getDeptChild(deptId);
		if (Func.isNotEmpty(deptChild)) {
			for (Dept dept : deptChild) {
				ids.add(dept.getId());
			}
		}
		return baseMapper.selectElevatorCountByIds(ids);
	}

	@Override
	public List<DeptStatisticalVO> deptMaintenanceStatisticalTree(Integer status) {

		// 构建树
		List<Long> removeIds = new ArrayList<>();
		List<DeptStatisticalVO> deptList = baseMapper.deptMaintenanceStatisticalTree(AuthUtil.getTenantId(),status);
		for (DeptStatisticalVO parent : deptList) {
			if (parent.getType() == 1 && parent.getTotal() == 0) {
				removeIds.add(parent.getId());
			}
			List<DeptStatisticalVO> children = new ArrayList<>();
			for (DeptStatisticalVO child : deptList) {
				if (child.getParentId().equals(parent.getId())) {
					removeIds.add(child.getId());
					if (child.getType() != 1 || child.getTotal() != 0) {
						children.add(child);
					}
				}
			}
			parent.getChildren().addAll(children);
		}
		// list移除树的child元素
		Iterator<DeptStatisticalVO> deptTreeIterator = deptList.iterator();
		while (deptTreeIterator.hasNext()) {
			if (removeIds.contains(deptTreeIterator.next().getId())) {
				deptTreeIterator.remove();
			}
		}
		return deptList;
	}


	@Override
	public List<Dept> listByIdsOrderByIds(List<Long> ancestorsIds) {
		return baseMapper.listByIdsOrderByIds(ancestorsIds);
	}

	@Override
	public List<DeptUserMemberVO> deptUserMemberAmountTree(String tenantId) {
		List<DeptUserMemberVO> result = new ArrayList<>();
		List<DeptUserMemberVO> list = baseMapper.deptUserMemberAmountTree(tenantId);
		if (Func.isNotEmpty(list)) {
			result = list.stream().filter(e -> e.getType() == 1).collect(Collectors.toList());
			result = ForestNodeMerger.merge(result);
			result.addAll(list.stream().filter(e -> e.getType() == 2 && e.getParentId() == 0).collect(Collectors.toList()));
			this.findChildren(result, list);
		}
		return result;
	}

	@Override
	public List<Long> selectDeptAndAllChildIds(List<Long> deptIds) {
		return this.selectDeptAndAllChildDepts(deptIds).stream().map(Dept::getId).collect(Collectors.toList());
	}

	@Override
	public List<Dept> selectDeptAndAllChildDepts(List<Long> deptIds) {
		List<Dept> deptList = super.list(Wrappers.<Dept>lambdaQuery().eq(Dept::getTenantId,AuthUtil.getTenantId()));
		if(Func.isEmpty(deptIds)){
			return deptList;
		}
		List<Dept> result = new ArrayList<>();
		deptIds.forEach(e -> {
			result.addAll(deptList.stream().filter(d -> d.getId().equals(e) || d.getAncestors().contains(String.valueOf(e))).collect(Collectors.toList()));
		});
		return new ArrayList<>(result.stream().collect(Collectors.toMap(
				Dept::getId,   // 键：去重依据的属性
				p -> p,          // 值：对象本身
				(existing, replacement) -> existing // 合并函数：保留现有值
			)).values());
	}

	private void findChildren(List<DeptUserMemberVO> result, List<DeptUserMemberVO> list) {
		result.forEach(e -> {
			e.getChildren().addAll(list.stream().filter(j -> j.getType() == 2 && j.getParentId().equals(e.getId())).collect(Collectors.toList()));
			if (e.getChildren().size() > 0) {
				this.findChildren(e.getChildren(), list);
			}
		});
	}

}
